package com.yunji.framework_template.common.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import com.yunji.framework_template.common.util.Jackson2Util;
import com.yunji.framework_template.common.util.ObjectUtil;

/**
 * 全局异常处理.
 * 
 * @author qingwu
 * @date 2014-2-8 下午5:53:23
 */
@ControllerAdvice
@RestControllerAdvice
@Primary
public class GlobalExceptionHandler {

    /**
     * 日志.
     */
    private static final Logger logger      = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * response编码.
     */
    private String              contentType = "UTF-8";

    /**
     * 404页面.
     */
    private String              errorUrl    = "/error";

    /**
     * 处理全局异常.
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ModelAndView handleError(HttpServletRequest request, HttpServletResponse response, Exception e) {
        logger.error("Reuqest url " + request.getRequestURI() + " exception happened:" + e.getMessage(), e);
        try {
            if (!ObjectUtil.isEmpty(request.getHeader("X-Requested-With"))) {// ajax请求返回指定的请求，而不是跳转到一个指定的页面
                Response<Boolean> globalResponse = ResponseFactory.getDefaultFailureResponse();
                globalResponse.setData(false);
                globalResponse.setMessage("The request could not be completed, server invoke error.");
                Jackson2Util.writeJson(response, globalResponse);
                return new ModelAndView();
            } else {// 页面跳转
                return new ModelAndView(errorUrl);
            }
        } catch (Throwable e1) {
            logger.error("Exception happened when handle exception, the message is:" + e1.getMessage(), e1);
            return new ModelAndView(errorUrl);
        }
    }

}
